package com.geeke.sys.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;

import com.geeke.common.service.CrudService;
import com.geeke.common.data.PageRequest;
import com.geeke.common.data.Parameter;
import com.geeke.config.exception.CommonJsonException;

import com.geeke.sys.dao.RoleDao;
import com.geeke.sys.entity.Role;
import com.geeke.utils.ResultUtil;
import com.geeke.utils.constants.ErrorEnum;
import com.google.common.collect.Lists;

/**
 * 角色表 Service
 */
@Service("roleService")
@Transactional(readOnly = true)
public class RoleService extends CrudService<RoleDao, Role> {

    @Transactional(readOnly = false)
    @Override
    public Role save(Role role) {
        // 重复性检查
        List<Parameter> params = Lists.newArrayList();
        
        // 编号重复性检查
        params.clear();
        params.add(new Parameter("role.code", "=", role.getCode()));
        params.add(new Parameter("role.del_flag", "=", role.getDelFlag()));
        params.add(new Parameter("role.company_id", "=", role.getCompany().getId()));

        if(!StringUtils.isBlank(role.getId())) {
          params.add(new Parameter("role.id", "<>", role.getId()));
        }

        if(this.dao.count(new PageRequest(params)) > 0) {
            throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "已存在相同编号"));
        }

        // 名称重复性检查
        params.clear();
        params.add(new Parameter("role.name", "=", role.getName()));
        params.add(new Parameter("role.del_flag", "=", role.getDelFlag()));
        params.add(new Parameter("role.company_id", "=", role.getCompany().getId()));

        if(!StringUtils.isBlank(role.getId())) {
          params.add(new Parameter("role.id", "<>", role.getId()));
        }

        if(this.dao.count(new PageRequest(params)) > 0) {
            throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "已存在相同名称"));
        }

        return super.save(role);
    }
} 